import os
import json
from pathlib import Path
from core.cfg import CFG
from core.log import logging
from TDhelper.generic.randGetValue import getValue
from core.token.meta import REQUEST_MANAGER,interface_token,attribute


'''
http header key
'''
class ENVIRONMENT_ENUM:
    development= "development"
    production= "production"
    test= "test"
SERVICE_STATE= {"state":False,"msg":""}
try:
    RUN_MODE= os.environ.get("run_mode").lower()
    #PRODUCTION= os.environ.get("PRODUCTION")
    #PRODUCTION= False if PRODUCTION.lower()=="false" else True
except Exception as e:
    RUN_MODE= "test"
    #PRODUCTION= False
if RUN_MODE=="production":
    ENVIRONMENT= ENVIRONMENT_ENUM.production
elif RUN_MODE=="development":
    ENVIRONMENT= ENVIRONMENT_ENUM.development
elif RUN_MODE=="test":
    ENVIRONMENT= ENVIRONMENT_ENUM.test
else:
    ENVIRONMENT= ENVIRONMENT_ENUM.development
logging.info('Run Environment: %s'%ENVIRONMENT)

'''token collects manage class.
'''
class TOKEN_MANAGE(interface_token):
    SAAS_ACCESS_SOURCE= "HTTP_ACCESS_SOURCE"
    SAAS_API_TOKEN= "HTTP_API_TOKEN"

'''system path init.
    BASE_BASE_DIR: system root path.
    BASE_LOG_DIR: system log path.
    cf_path: system config ini path.
    register_permission_path: system permission register config json path
'''
BASE_BASE_DIR = Path(__file__).resolve().parent.parent
BASE_LOG_DIR = os.path.join(BASE_BASE_DIR, "logs")
cfg_path = os.path.join(BASE_BASE_DIR, "config", "cfg-"+ENVIRONMENT+".ini")
register_permission_path = os.path.join(
    BASE_BASE_DIR, r"config","regist_conf", "permission.json")
    
EXCLUDE_FILTER=['api/notify','api/sniffer','api/publish_choices','api/ticket']

'''exclude_filter formatter.
   exclude both '/' char 
'''
for offset in range(0,len(EXCLUDE_FILTER)):
    EXCLUDE_FILTER[offset]=EXCLUDE_FILTER[offset].strip('/')
    
'''system register config
    RPC_REGISTER_LIST: need auto register PRC service.
    EVENT_REGISTER_LIST: need auto register EVENT.
'''
# RPC_REGISTER_LIST format(["namespace:classname",]) e.g. ["api.views:xxxViewSet"]
RPC_REGISTER_LIST = []

# EVENT_REGISTER_LIST format(["namespace:classname",]) e.g. ["api.views:xxxViewSet"]
EVENT_REGISTER_LIST = []

'''conf read.
    service: service dict.
    host: service hosts.
    BASE_ALLOWED_HOSTS: allowed hosts.
    BASE_REMOTE_CONFIG: remote config value.
    REST_FRAMEWORK_DOMAIN:  you can set APIRequestFactory()._current_scheme_host with this value.
    RPC_LOADS: load RPC service list.
'''
cfg= None
try:
    cfg = CFG(cfg_path)
except Exception as e:
    logging.error(e.args[0])
assert cfg!=None, "cfg instance is None, configure file(%s). see more in log file."%cfg_path
# Loadd inspection configure;
INSPECTION_CONF= []
if cfg.INSPECTION_CONF_PATH:
    with open(os.path.join(BASE_BASE_DIR,cfg.INSPECTION_CONF_PATH),mode='r') as f:
        INSPECTION_CONF= json.load(f)[ENVIRONMENT]
        f.close()
    
SYS_CODING=cfg.CODING
'''
cache conf
'''
CACHE_CONF={
    "ENGINE":cfg.CACHE_ENGINE,
    "options":{
        "host":cfg.CACHE_HOST,
        "db":cfg.CACHE_DB,
        "user":cfg.CACHE_USER,
        "passwd":cfg.CACHE_PASSWD
    }
}
service = {
    "name": cfg.SERVICE_NAME,
    "description": cfg.SERVICE_DESCRIPTION,
    "key": cfg.SERVICE_KEY,
    "accessSecret": cfg.SERVICE_ACCESS_SECRET,
    "httpProtocol": cfg.SERVICE_PROTOCOL
}
hosts = []
for item in str.split(cfg.SERVICE_HOST):
    o = str.split(item, ":")
    if(len(o) == 0):
        hosts.append({"host": o[0], "port": 80})
    else:
        hosts.append({"host": o[0], "port": o[1]})
BASE_ALLOWED_HOSTS = str.split(
    cfg.ALLOWED_HOSTS, '|') if cfg.ALLOWED_HOSTS else ["*"]
BASE_REMOTE_CONFIG = {
    "token": cfg.SERVICE_ACCESS_SECRET,
    "allowClients": ','.join(BASE_ALLOWED_HOSTS)
}

RPC_LOADS = cfg.LOAD_REMOTE_SERVIERS


def getDomain():
    return cfg.SERVICE_PROTOCOL + getValue(str.split(cfg.SERVICE_HOST))

# service auto register configure.
# rpc: regist rpc service.
# configure: regist micro service's environment variable to remote configure center.
# permission: regist micro service's permissions to permission center.
# event: regist micro service's even to event center.
EXEC_REGIST_METHOD=['rpc','configure','permission','event']

REST_FRAMEWORK_DOMAIN = getDomain()
        
    
    
